const express = require("express")
var jwt = require('jsonwebtoken');
var expressjwt = require("express-jwt");
const app = express()
const cors = require("cors")

//图片处理测试
// const sharp = require('sharp')
// const img_name = '../public/home1.png'
// const resize_img_name = '../public/home2.png'
// sharp(img_name).resize(100,100).toFile(resize_img_name, err => {
//         console.log("图片裁剪");
//         if (err) console.log(err)
//     })

app.use(cors())
const bodyParser = require("body-parser")

app.use(bodyParser.urlencoded({ extended: false }))
//自定义加密字符串
const secretKey = "item qiu"
app.use(express.static("../public"))
//只要配置express -jwt 这个中间件 就可以把解析出来的用户信息挂载到req.user属性上

app.use(expressjwt({ secret: secretKey, algorithms: ["HS256"], credentialsRequired: false, }).unless({ path: [/^\/api\//] }));

app.post("/api/login", (req, res) => {
    console.log(req.body);
    const userInfo = req.body
    if (userInfo.username != "admin" || userInfo.password !== "000000") {
        return res.send({
            status: 400,
            message: "登录失败"
        })
    }
    // 加密username 并生效时间为30s
   const tokenStr = jwt.sign({data: userInfo.username}, secretKey, { expiresIn: '1h' });
    console.log(req.user);
    res.send({
        statsu: 200,
        message: "登录成功",
        data:tokenStr
    })
})
//解析获取用户信息
app.get("/admin/getadmin",(req,res)=>{
    console.log(req.user);
    res.send({
        status:200,
        msg:"获取信息成功",
        data:req.user
    })
})
//注册全局因为token解析失败引起的异常可以通过全局中间件来解决
app.use((err,req,res,next)=>{
    //token解析失败导致的错误
    if(err.name==="UnauthorizedError"){
        return res.send({
            staus:401,
            msg:"无效token或token已过期"
        })
    }else{
        res.send({
            status:500,msg:"未知错误"
        })
    }
})
app.listen(8090)